<?php
declare (strict_types = 1);

namespace app\model\communal;

use app\model\concern\AmisTrait;
use think\Model;
use think\db\Query;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsToMany;

class RoleModel extends Model
{
    use AmisTrait;

    /**
     * 数据库配置
     *
     * @var string
     */
    protected $connection = 'communal';

    /**
     * 主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $table = '02_system_role';

    /**
     * 自动时间戳
     *
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间字段设置
     *
     * @var string
     */
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 软删除
     */
    use SoftDelete;
    protected $deleteTime = 'delete_at';
    protected $defaultSoftDelete = 0;

    /**
     * 展示字段名
     *
     * @var string[]
     */
    public static $column = ['id', 'admin_id', 'name', 'state', 'created_at'];

    /**
     * 搜索字段名
     *
     * @var string[]
     */
    public static $searchColumn = ['id', 'admin_id', 'company_id', 'name', 'state', 'createtime'];

    /**
     * 新增字段
     *
     * @var string[]
     */
    public static $saveColumn = ['name', 'state'];

    /**
     * 更新字段
     *
     * @var string[]
     */
    public static $updateColumn = ['id', 'name', 'state'];

    /**
     * company_id搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchCompanyIdAttr(Query $query, $value)
    {
        if (!is_null($value) && strlen((string)$value) > 0) {
            $query->where('company_id', $value);
        }
    }

    /**
     * 关联员工
     *
     * @return HasMany
     */
    public function roleAdmin(): HasMany
    {
        return $this->hasMany(AdminModel::class, 'role_id', 'id');
    }

    /**
     * 关联角色权限中间表
     *
     * @return HasMany
     */
    public function hasManyPermissions(): HasMany
    {
        return $this->hasMany(RolePermissionsModel::class, 'role_id', 'id');
    }

    /**
     * 关联权限 多多
     *
     * @return BelongsToMany
     */
    public function belongsToManyPermissions(): BelongsToMany
    {
        return $this->belongsToMany(PermissionsModel::class, RolePermissionsModel::class, 'permissions_id', 'role_id');
    }
}
